<!--  -->
<template>
  <div>
    <div class="comments-area">
      <div class="widget-header-2 position-relative mb-30">
        <h5 class="mt-5 mb-30">评论区</h5>
      </div>
      <div v-loading="isOp">
        <div v-for="(item,i) in comments.records" :key="i">
          <!-- 主评论 -->
          <div class="comment-list wow fadeIn animated pt-0 pb-0" v-if="item.parentid == null">
            <div class="single-comment justify-content-between d-flex ml-0">
              <div class="user justify-content-between d-flex">
                <div class="thumb" >
                  <router-link class="author-avatar" :to="{ name: 'author', params: { id:item.userid } }">
                    <img :src="users.get(item.userid).avater" alt="">
                  </router-link>
                </div>
                <div class="desc">
                  <div class="d-flex justify-content-between">
                    <div class="d-flex align-items-center">
                      <h5 >
                          <router-link class="author-avatar" :to="{ name: 'author', params: { id:item.userid } }">{{users.get(item.userid).nickname}}</router-link>
                      </h5>

                    </div>

                  </div>
                  <p class="comment mt-5">
                    {{item.content}}
                  </p>
                  <el-row :gutter="20" v-if="current!= null && current.id == item.id">
                    <el-col :span="20">
                      <input v-model="content" class="form-control" type="text" :placeholder="'@'+item.userid">
                    </el-col>
                    <el-col :span="4">
                      <el-button @click="comment" :loading="isComment" type="primary" circle icon="el-icon-finished">
                      </el-button>
                    </el-col>
                  </el-row>
                </div>
              </div>
            </div>

            <p class="date float-right">{{$commons.dateStr(item.timestamp)}} 评论</p>
            <div class="reply-btn ml-10 float-right">
              <offence :user="users.get(item.userid)" type="评论" :content="item.content" :target="item.id"></offence>
            </div>
            <div class="reply-btn ml-10 float-right">
              <a href="javascript:void(0)" class="btn-reply"
                @click="replace(item)">{{current!= null && current.id == item.id?'收起':'回复'}}</a>
            </div>
            <div class="reply-btn ml-10 float-right" v-if="item.size > 0 && (item.size-comments2.get(item.id).records.length)>0">
              <a href="javascript:void(0)" class="btn-reply" @click="getMore(item,i)">{{(item.size-comments2.get(item.id).records.length)==0?'查看更多':'查看剩余的'+(item.size-comments2.get(item.id).records.length)+'条评论'}}</a>
            </div>
            <div class="reply-btn ml-10 float-right" v-if="hasMain && item.id == comments.records[comments.records.length-1].id && (item.size-comments2.get(item.id).records.length)==0">
              <a href="javascript:void(0)" class="btn-reply" @click="getMore(item,i)">查看更多</a>
            </div>
            <el-divider></el-divider>
          </div>

          <!-- 附评论 -->
          <div v-for="(child,idx) in comments2.get(item.id).records" :key="idx">
            <div class="comment-list wow fadeIn animated pt-0 pb-0" v-if="child.parentid == item.id">
              <div class="single-comment justify-content-between d-flex ml-0 pl-80">
                <div class="user justify-content-between d-flex">
                  <div class="thumb">
                    <router-link class="author-avatar" :to="{ name: 'author', params: { id:child.userid } }">
                      <img :src="users.get(child.userid).avater" alt="">
                    </router-link>
                  </div>
                  <div class="desc">
                    <div class="d-flex justify-content-between">
                      <div class="d-flex align-items-center">
                        <h5>
                              <router-link class="author-avatar" :to="{ name: 'author', params: { id:child.userid } }">{{users.get(child.userid).nickname}}</router-link>
                        </h5>
                      </div>
                    </div>
                    <p class="comment mt-5">
                      回复
                      <span class="text-info">
                          <router-link class="author-avatar text-info" :to="{ name: 'author', params: { id:users.get(child.replaceid).userid } }">{{users.get(child.replaceid).nickname}}</router-link>
                          <span>：</span>
                          </span>
                      <span>{{child.content}}</span>
                    </p>
                    <el-row :gutter="20" v-if="current!= null && current.id == child.id">
                      <el-col :span="20">
                        <input v-model="content" class="form-control" type="text" :placeholder="'@'+child.userid">
                      </el-col>
                      <el-col :span="4">
                        <el-button @click="comment" :loading="isComment" type="primary" circle icon="el-icon-finished">
                        </el-button>
                      </el-col>
                    </el-row>
                  </div>
                </div>
              </div>
              <p class="date float-right">{{$commons.dateStr(child.timestamp)}} 评论</p>
              <div class="reply-btn ml-10 float-right">
              <offence :user="users.get(child.userid)" :content="child.content" type="评论" :target="child.id"></offence>
            </div>
              <div class="reply-btn ml-10 float-right">
                <a href="javascript:void(0)" class="btn-reply"
                  @click="replace(child)">{{current!= null && current.id == child.id?'收起':'回复'}}</a>
              </div>
              <el-divider></el-divider>
            </div>
          </div>

        </div>
      </div>
    </div>
    <!--comment form-->
    <div class="comment-form wow fadeIn animated">
      <div class="widget-header-2 position-relative mb-30">
        <h5 class="mt-5 mb-30">我的评论</h5>
      </div>
      <div v-if="current == null" class="form-contact comment_form" action="#" id="commentForm">
        <div class="row">
          <div class="col-12">
            <div class="form-group">
              <textarea v-model="content" class="form-control w-100" name="comment" id="comment" cols="30" rows="3"
                placeholder="无真相，不评论"></textarea>
            </div>
          </div>
        </div>
        <div class="form-group">
          <el-button @click="comment" :loading="isComment" type="primary" circle icon="el-icon-finished"></el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  //这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
  //例如：import 《组件名称》 from '《组件路径》';
  import offence from './offence.vue'
  export default {
    //import引入的组件需要注入到对象中才能使用
    components: {
      offence
    },
    props: ["id"],
    data() {
      //这里存放数据
      return {
        isOp: false,
        hasMain:true,
        current: null,
        content: '',
        docId: -1,
        isComment: false,
        comments: {
          current: 1,
          size: 5,
          records: []
        },
        comments2: new Map(),
        users: new Map(),
        isMain: true
      };
    },
    //监听属性 类似于data概念
    computed: {},
    //监控data中的数据变化
    watch: {
      id: function (n, o) {
        this.docId = n;
        this.getComments();
      }
    },
    //方法集合
    methods: {
      async getUs() {
        var arr = new Set();
        for (const c of this.comments.records) {
          if (!this.users.has(c.userid)) {
            arr.add(c.userid);
          }
          if (!this.users.has(c.replaceid)) {
            arr.add(c.replaceid);
          }
        }
        for (const cs of this.comments2.values()) {
          for (const c of cs.records) {
            if (!this.users.has(c.userid)) {
              arr.add(c.userid);
            }
            if (!this.users.has(c.replaceid)) {
              arr.add(c.replaceid);
            }
          }

        }
        if (arr.size == 0) {
          return;
        }
        const pram = {
          ids: Array.from(arr).sort()
        }
        var res = await this.$api.user.users(pram);
        if (res.code == 20000) {
          for (const u of res.data) {
            this.users.set(u.id, u);
          }
        }
        this.$forceUpdate()
      },
      async getMore(data, i) {
        this.isOp = true;
        if (data.id == this.comments.records[this.comments.records.length - 1].id) {
          // 主评论最后一个
          if (this.comments.current >= this.comments.pages) {
            // 没有主评论了，查看内部评论
            if (this.comments2.get(data.id).pages != -1 && this.comments2.get(data.id).current >= this.comments2.get(
                data.id).pages) {
              //内评论也没有了
              this.isOp = false;
              this.hasMain = false;
              Notiflix.Notify.Info('已经没有更多了');
              return;
            }
            const pram = {
              comment: {
                parentid: data.id,
                objectid: data.objectid
              },
              page: {
                current: this.comments2.get(data.id).current + 1,
                size: this.comments2.get(data.id).size
              }
            }
            var res = await this.$api.comment.getComment(pram);
            if (res.code == 20000) {
              // 追截内评论
              res.data.records = this.comments2.get(data.id).records.concat(res.data.records);
              // 覆盖
              this.comments2.set(data.id, res.data);
              this.getUs();
            }
          } else {
            // 追加下一页主评论
            this.comments.current = this.comments.current + 1;
            this.getComments();
          }

        } else {
          // 查看内部评论
          if (this.comments2.get(data.id).pages != -1 && this.comments2.get(data.id).current >= this.comments2.get(
              data.id).pages) {
            //内评论也没有了
            this.isOp = false;
            Notiflix.Notify.Info('没有更多了');
            return;
          }
          const pram = {
            comment: {
              parentid: data.id,
              objectid: data.objectid
            },
            page: {
              current: this.comments2.get(data.id).current + 1,
              size: this.comments2.get(data.id).size
            }
          }
          var res = await this.$api.comment.getComment(pram);
          if (res.code == 20000) {

            // 追截内评论
            res.data.records = this.comments2.get(data.id).records.concat(res.data.records);
            // 覆盖
            this.comments2.set(data.id, res.data);
            this.getUs();
          }
        }

        this.$forceUpdate();
        this.isOp = false;
      },
      async getComments() {
        this.isOp = true;
        const pram = {
          page: {
            current: this.comments.current,
            size: this.comments.size
          },
          comment: {
            objectid: this.id,
            parentid:null
          }
        }
        var res = await this.$api.comment.getComment(pram);
        if (res.code == 20000) {
          this.comments.records = this.comments.records.concat(res.data.records);
          this.comments.pages = res.data.pages;
          for (const c of res.data.records) {
            if (!this.comments2.has(c.id)) {
              // 初始化Map
              var c2 = {
                current: 0,
                size: 5,
                pages: -1,
                records: []
              }
              this.comments2.set(c.id, c2);
              this.getUs();
            }
          }
        }
        this.getUs();
        this.$forceUpdate()
        this.isOp = false;
      },
      async comment() {
        this.isComment = true;
        if (this.$commons.isEmptyString(this.content)) {
          return
        }
        const pram = {
          content: this.content,
          parentid: this.current == null ? null : this.current.parentid == null ? this.current.id : this.current
            .parentid,
          replaceid: this.current == null ? null : this.current.userid,
          objectid: this.id
        }
        await this.$api.comment.save(pram);
        this.isComment = false;
      },
      replace(data) {
        if (data == this.current) {
          this.current = null;
        } else {
          this.current = data;
        }
      }
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created() {

    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {
      
      console.log(this.$commons.dateStr('1646628346625'))
      // console.log(this.id);
      // this.getComments();
    },
    beforeCreate() {}, //生命周期 - 创建之前
    beforeMount() {}, //生命周期 - 挂载之前
    beforeUpdate() {}, //生命周期 - 更新之前
    updated() {}, //生命周期 - 更新之后
    beforeDestroy() {}, //生命周期 - 销毁之前
    destroyed() {}, //生命周期 - 销毁完成
    activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
  }

</script>
<style scoped>

</style>
